﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Net;
using System.IO;
using System.Reflection;

using WebPALTT.Lib;
using System.Threading;

namespace WebPALTT.UI
{
    public partial class ApplicationForm : Form
    {
        TestDefinition mTestDef;
        FileInfo mFileInfo;
        bool mUnsavedChanges;
        TestResultCollection mResultsCollection;

        #region Constructors
        
        public ApplicationForm()
        {
            InitializeComponent();
            InitializeResultsTempFile();

            mTestDef = new TestDefinition();
            mUnsavedChanges = false;
            RefreshTestDefView();
        }

        public ApplicationForm(string path) : this()
        {
            mFileInfo = new FileInfo(path);
            if (mFileInfo.Exists)
                mTestDef = FileSerialization.DeSerializeObject<TestDefinition>(path);
            else
                mFileInfo = null;
            RefreshTestDefView();
        }
        
        #endregion

        #region Test Definition
        
        private void RefreshTestDefView()
        {
            if (mFileInfo == null)
                this.Text = "WebPALTT";
            else
                this.Text = "WebPALTT - " + mFileInfo.FullName + (mUnsavedChanges ? "*" : "");

            lb_Scenarios.Items.Clear();
            splitContainer1.Panel2.Enabled = false;
            if (mTestDef == null)
                return;
            if (mTestDef.RunMode == RunMode.Concurrent)
                cb_Run_Test_Concurrently.Checked = true;
            else if (mTestDef.RunMode == RunMode.Sequential)
                cb_Run_Test_Concurrently.Checked = false;

            foreach (Scenario scene in mTestDef.Scenarios)
                lb_Scenarios.Items.Add(scene.Name);

            tb_Scene_Name.Text = "";
            tb_Scene_Description.Text = "";
            nud_Scene_TotalVUsers.Value = 1;
            cb_Scene_RunMode.SelectedItem = "Concurrent";
            nud_Scene_StartingVUsers.Value = 1;
            nud_Scene_IncreaseVUsers.Value = 0;
            nud_Scene_RampUpTimeSpan.Value = 0;
            rb_Scene_StopVUsers.Checked = true;
            rb_Scene_StopTime.Checked = false;
            nud_Scene_StopTimeDuration.Value = 0;
            nud_Scene_StopTimeDuration.Enabled = false;
            gb_Scene_RampUpLoad.Enabled = false;
        }
        
        private void RunTest()
        {
            AppDomain appDomain = AppDomain.CreateDomain("TestRunDomain");
            TestRunner runner = (TestRunner)appDomain.CreateInstanceFromAndUnwrap(
                Assembly.GetAssembly(typeof(TestRunner)).Location,
                typeof(TestRunner).FullName);

            mTestDef = runner.RunTest(mTestDef);
            
            AppDomain.Unload(appDomain);
            
            RefreshLog();
            tabControl1.SelectedTab = tp_Log;
            if (mTestDef.Results == null)
                return;
            TestResult results = new TestResult(mTestDef.Results.ToArray(), DateTime.Now, mFileInfo == null ? "Test": mFileInfo.Name, mTestDef.RunDuration);
            mResultsCollection.Add(results);
            int max = Properties.Settings.Default.Results_Gen_MaxCount;            
            if (max > 0 && mResultsCollection.Count > max)
                for (int i = 0; i < (mResultsCollection.Count - max); i++)
                    mResultsCollection.RemoveAt(i);

            SaveResultsTempFile();
            SaveResults(results);
        }
        
        private bool CheckSave()
        {
            if (!mUnsavedChanges)
                return true;

            DialogResult result = MessageBox.Show(this, "Do you want to save the changes to this project?",
                "WebPALTT", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
                return SaveProject();
            else if (result == DialogResult.No)
                return true;
            else
                return false;
        }

        private bool SaveProject(bool toNewFile = false)
        {
            if (mTestDef == null)
                return false;

            if (toNewFile || mFileInfo == null)
            {
                SaveFileDialog sfdialog = new SaveFileDialog();
                sfdialog.Title = "Save Project";
                sfdialog.Filter = "Scalability Project|*.spf|All Files|*.*";
                sfdialog.AddExtension = true;
                sfdialog.DefaultExt = "spf";
                if (sfdialog.ShowDialog(this) == DialogResult.OK)
                {
                    mFileInfo = new FileInfo(sfdialog.FileName);
                }else
                    return false;
            }
            try
            {
                FileSerialization.SerializeObject<TestDefinition>(mTestDef, mFileInfo.FullName);
                mUnsavedChanges = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error Occured During Save Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            RefreshTestDefView();
            return true;
        }

            #region Selected Scenario Options

        private void b_Create_New_Scenario_Click(object sender, EventArgs e)
        {
            scenarioBuilderToolStripMenuItem_Click(null, null);
        }

        private void b_Add_Scenario_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdialog = new OpenFileDialog();
            ofdialog.Title = "Open Scenario";
            ofdialog.Filter = "Binary File|*.bin|All files|*.*";
            ofdialog.Multiselect = false;
            if (ofdialog.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    Scenario scene = FileSerialization.DeSerializeObject<Scenario>(ofdialog.FileName);
                    string[] errors = scene.Validate();
                    if (errors.Length > 0)
                    {
                        string validationMessage = "The following validation errors occured:\r\n\r\n";
                        foreach (string s in errors)
                            validationMessage += s + "\r\n";
                        validationMessage += "\r\nDo you want to continue loading this scenario?";
                        DialogResult result = MessageBox.Show(this, validationMessage, "Scenario Validation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (!result.Equals(DialogResult.Yes))
                            return;
                    }
                    if (String.IsNullOrEmpty(scene.Name))
                        scene.Name = "Scenario (" + (mTestDef.Scenarios.Count + 1) + ")";
                    mTestDef.Scenarios.Add(scene);                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error Occured During Import", MessageBoxButtons.OK, MessageBoxIcon.Error); 
                    return; 
                }
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
                
                RefreshTestDefView();
                lb_Scenarios.SelectedIndex = lb_Scenarios.Items.Count - 1;
            }
        }

        private void b_Remove_Scenario_Click(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex == -1)
                return;
            mTestDef.Scenarios.RemoveAt(lb_Scenarios.SelectedIndex);
            if (!mUnsavedChanges)
                mUnsavedChanges = true;
            RefreshTestDefView();
        }
        
        private void b_Edit_Scenario_Click(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex == -1)
                return;
            ScenarioBuilder builder = new ScenarioBuilder(mTestDef.Scenarios[lb_Scenarios.SelectedIndex]);
            if (builder.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { }
            if (!mUnsavedChanges)
                mUnsavedChanges = true;
        }

            #endregion

            #region Selected Scenario Events

        private void lb_Scenarios_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex == -1)
            { 
                splitContainer1.Panel2.Enabled = false; 
                return; 
            }
            splitContainer1.Panel2.Enabled = true;

            tb_Scene_Name.Text = mTestDef.Scenarios[lb_Scenarios.SelectedIndex].Name;
            tb_Scene_Description.Text = mTestDef.Scenarios[lb_Scenarios.SelectedIndex].Description;

            if (mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions == null)
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions = new RunConditions();
            RunConditions conditions = mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions;
            nud_Scene_TotalVUsers.Value = conditions.VirtualUsers;
            switch(conditions.RunMode)
            {
                case RunMode.Concurrent:
                    cb_Scene_RunMode.SelectedItem = "Concurrent";
                    break;
                case RunMode.Sequential:
                    cb_Scene_RunMode.SelectedItem = "Sequential";
                    break;
                case RunMode.RampUp:
                    cb_Scene_RunMode.SelectedItem = "Ramp up";
                    break;
            }
            nud_Scene_StartingVUsers.Value = conditions.StartingUsers;
            nud_Scene_IncreaseVUsers.Value = conditions.RampUpUsers;
            nud_Scene_RampUpTimeSpan.Value = conditions.RampUpTimeSpan;
            rb_Scene_StopVUsers.Checked = conditions.StopOnUserCount;
            rb_Scene_StopTime.Checked = conditions.StopOnMaxTime;
            nud_Scene_StopTimeDuration.Value = conditions.MaxTime;
        }

        private void cb_Scene_RunMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex < 0)
                return;
            if (cb_Scene_RunMode.SelectedItem.Equals("Sequential"))
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.RunMode = RunMode.Sequential;
                gb_Scene_RampUpLoad.Enabled = false;
            }
            else if (cb_Scene_RunMode.SelectedItem.Equals("Concurrent"))
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.RunMode = RunMode.Concurrent;
                gb_Scene_RampUpLoad.Enabled = false;
            }
            else if (cb_Scene_RunMode.SelectedItem.Equals("Ramp up"))
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.RunMode = RunMode.RampUp;
                gb_Scene_RampUpLoad.Enabled = true;
            }
            else
                gb_Scene_RampUpLoad.Enabled = false;
            
            if (!mUnsavedChanges)
                mUnsavedChanges = true;
            
        }

        private void nud_Scene_TotalVUsers_ValueChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.VirtualUsers = Convert.ToInt32(nud_Scene_TotalVUsers.Value);
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }

        private void nud_Scene_StartingVUsers_ValueChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.StartingUsers = Convert.ToInt32(nud_Scene_StartingVUsers.Value);
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }

        private void nud_Scene_IncreaseVUsers_ValueChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.RampUpUsers = Convert.ToInt32(nud_Scene_IncreaseVUsers.Value);
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }

        private void nud_Scene_RampUpTimeSpan_ValueChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.RampUpTimeSpan = Convert.ToInt32(nud_Scene_RampUpTimeSpan.Value);
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }

        private void rb_Scene_StopVUsers_CheckedChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex < 0)
                return;
            if (rb_Scene_StopVUsers.Checked)
            {
                rb_Scene_StopTime.Checked = false;
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.StopOnUserCount = true;
            }
            else
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.StopOnUserCount = false;
            if (!mUnsavedChanges)
                mUnsavedChanges = true;
        }

        private void rb_Scene_StopTime_CheckedChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex < 0)
                return;
            if (rb_Scene_StopTime.Checked)
            {
                nud_Scene_StopTimeDuration.Enabled = true;
                rb_Scene_StopVUsers.Checked = false;
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.StopOnMaxTime = true;
            }
            else
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.StopOnMaxTime = false;
                nud_Scene_StopTimeDuration.Enabled = false;
            }
            if (!mUnsavedChanges)
                mUnsavedChanges = true;
        }

        private void nud_Scene_StopTimeDuration_ValueChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].RunConditions.MaxTime = Convert.ToInt32(nud_Scene_StopTimeDuration.Value);
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }
        
        private void cb_Run_Test_Concurrently_CheckedChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.RunMode = cb_Run_Test_Concurrently.Checked ? RunMode.Concurrent : RunMode.Sequential;
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }
        
        private void tb_Scene_Name_TextChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].Name = tb_Scene_Name.Text;
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }

        private void tb_Scene_Description_TextChanged(object sender, EventArgs e)
        {
            if (lb_Scenarios.SelectedIndex >= 0)
            {
                mTestDef.Scenarios[lb_Scenarios.SelectedIndex].Description = tb_Scene_Description.Text;
                if (!mUnsavedChanges)
                    mUnsavedChanges = true;
            }
        }

            #endregion

        #endregion        
        
        #region MessageLog

        private void RefreshLog()
        {
            lb_Log.Items.Clear();
            foreach (KeyValuePair<String, String> log in mTestDef.MessageLog)
                lb_Log.Items.Add(log.Key);
            tb_Log_Message.Text = "";
        }

        private void lb_Log_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(lb_Log.SelectedIndex >= 0)
                tb_Log_Message.Text = mTestDef.MessageLog[lb_Log.SelectedIndex].Value;
        }

        private void b_Log_Clear_Click(object sender, EventArgs e)
        {
            mTestDef.ClearMessageLog();
            RefreshLog();
        }
        #endregion        

        #region Results
        private void InitializeResultsTempFile()
        {
            FileInfo res_file = null;
            string filepath = Properties.Settings.Default.Results_Gen_TempPath;
            if (String.IsNullOrWhiteSpace(filepath))
            {
                res_file = new FileInfo("results.tmp");
                try
                {
                    if (!res_file.Exists)
                        res_file.Create().Close();
                }
                catch (Exception)
                {
                    res_file = new FileInfo(Path.Combine(Path.GetTempPath(), "results.tmp"));
                    try
                    {
                        if (!res_file.Exists)
                            res_file.Create().Close();
                    }
                    catch (Exception)
                    { res_file = null; }
                }
                if (res_file != null)
                {
                    Properties.Settings.Default.Results_Gen_TempPath = res_file.FullName;
                    Properties.Settings.Default.Save();
                }
            }
            else 
            {
                res_file = new FileInfo(filepath);
                if (!res_file.Exists)
                    res_file = null;
            }

            if (res_file != null)
            {
                res_file.Refresh();
                if (res_file.Length > 0)
                    mResultsCollection = FileSerialization.DeSerializeObject<TestResultCollection>(res_file.FullName);
                else
                    mResultsCollection = new TestResultCollection();
            }
            else
                mResultsCollection = new TestResultCollection();
            RefreshResultsView();
        }

        private void SaveResultsTempFile()
        {
            FileInfo res_file = null;
            string filepath = Properties.Settings.Default.Results_Gen_TempPath;
            if (String.IsNullOrWhiteSpace(filepath))
            {
                res_file = new FileInfo("results.tmp");
                try
                {
                    if (!res_file.Exists)
                        res_file.Create().Close();
                }
                catch (Exception)
                {
                    res_file = new FileInfo(Path.Combine(Path.GetTempPath(), "results.tmp"));
                    try
                    {
                        if (!res_file.Exists)
                            res_file.Create().Close();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show(this, "The results collection could not be saved to the application directory or temporary files.\r\n" +
                            "Any results not manually saved will be lost when the application closes.\r\n\r\n" +
                            "This is likely due to the access permissions for these folders.", "File Access Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        res_file = null;
                    }
                }
                if (res_file != null)
                {
                    Properties.Settings.Default.Results_Gen_TempPath = res_file.FullName;
                    Properties.Settings.Default.Save();
                }
            }
            else
            {
                res_file = new FileInfo(filepath);
                try
                {
                    if (!res_file.Exists)
                        res_file.Create().Close();
                }
                catch (Exception)
                {
                    MessageBox.Show(this, "The results collection could not be saved to the specified file.\r\n" +
                        "Any results not manually saved will be lost when the application closes.\r\n\r\n" +
                        "This is likely due to the access permissions for these folders.", "File Access Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    res_file = null;
                }
            }
            
            try
            {
                if (res_file != null)
                {
                    res_file.Refresh();
                    FileSerialization.SerializeObject<TestResultCollection>(mResultsCollection, res_file.FullName);
                }
            }
            catch (Exception)
            {
                MessageBox.Show(this, "An error has occured while trying to save the results collection to the location:\r\n\t" + 
                    res_file.FullName + "\r\n\r\n" +
                    "Any results not manually saved will be lost when the application closes.\r\n\r\n", 
                    "File Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
            RefreshResultsView();
        }

        private void RefreshResultsView() 
        {
            if (mResultsCollection == null)
                return;
            lb_ResultSets.Items.Clear();
            foreach (TestResult res in mResultsCollection)
                lb_ResultSets.Items.Add(res.Name + " - " + res.RunDate.ToLongDateString() + " " + res.RunDate.ToLongTimeString());
        }

        private void SaveResults(TestResult results, string format = null)
        {
            if (format == null)
                format = Properties.Settings.Default.Results_Gen_SaveFormat.Trim().ToUpper();
            else
                format = format.Trim().ToUpper();

            if (format.Equals("DATABASE"))
            {
                if (String.IsNullOrWhiteSpace(Properties.Settings.Default.Results_DB_Name))
                {
                    MessageBox.Show(this, "A database has not been configured to save the results to.\r\n" +
                        "Please set the database login information in the Options.", "Database Not Configured",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                try
                {
                    Results.SaveToDataBase(Properties.Settings.Default.Results_DB_Server, Properties.Settings.Default.Results_DB_Name,
                        Properties.Settings.Default.Results_DB_UseIntergrate, Properties.Settings.Default.Results_DB_Uid,
                        Properties.Settings.Default.Results_DB_Pwd, results);
                    MessageBox.Show(this, "Results have been successfully saved to the database [" + Properties.Settings.Default.Results_DB_Server + 
                        "].[" + Properties.Settings.Default.Results_DB_Name + "]", "Save Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                { MessageBox.Show(this, "An error occured during the save operation.\r\n" + ex.Message, "An Error Has Occured", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            }
            else
            {
                SaveFileDialog sfdialog = new SaveFileDialog();
                sfdialog.Title = "Save Results";
                sfdialog.Filter = "CSV|*.csv|XML|*.xml|HTML|.html|All Files|*.*";
                sfdialog.AddExtension = true;
                sfdialog.DefaultExt = "csv";
                if (sfdialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    { Results.SaveToFile(new FileInfo(sfdialog.FileName), results.Results, Properties.Settings.Default.Results_HTML_css); }
                    catch (Exception ex)
                    { MessageBox.Show(this, "An error occured during the save file operation.\r\n" + ex.Message, "An Error Has Occured", MessageBoxButtons.OK, MessageBoxIcon.Error); }
                }
            }
        }

        private void lb_ResultSets_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lb_ResultSets.SelectedIndex == -1)
            {
                rtb_ResultSummary.Rtf = "";
                return;
            }
            TestResult selected_result = mResultsCollection[lb_ResultSets.SelectedIndex];
            rtb_ResultSummary.Rtf = "{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Microsoft Sans Serif;}\\f0\\fs18\\pard " +
                "\\b Title: \\tab \\tab \\tab \\tab \\b0 " + selected_result.Name + "\\par \\b Execution Date: \\tab \\tab \\b0 " + selected_result.RunDate.ToLongDateString() +
                " " + selected_result.RunDate.ToLongTimeString() + "\\par \\par \\b Total Run Time (s): \\tab \\tab \\b0 " + selected_result.RunDuration.TotalSeconds +
                "\\par \\par \\b Total Virtual User Count: \\tab \\b0 " + selected_result.Results.Length + "\\par \\par " +
                "\\b Total Warnings: \\tab \\tab \\b0 " + selected_result.GetMessageCount(true, false) + "\\par \\b Total Errors: \\tab \\tab \\tab \\b0 " + 
                selected_result.GetMessageCount(false, true) + "}";
        }
        
        private void b_Results_Save_Click(object sender, EventArgs e)
        {
            if (lb_ResultSets.SelectedIndex == -1)
                return;

            SaveFileDialog sfdialog = new SaveFileDialog();
            sfdialog.Title = "Save Results";
            sfdialog.Filter = "Binary|*.bin|All Files|*.*";
            sfdialog.AddExtension = true;
            sfdialog.DefaultExt = "bin";
            if (sfdialog.ShowDialog(this) == DialogResult.OK)
                try
                { FileSerialization.SerializeObject<TestResult>(mResultsCollection[lb_ResultSets.SelectedIndex], sfdialog.FileName); }
                catch (Exception ex) { 
                    MessageBox.Show(this, "An error occured during the save file operation.\r\n" + ex.Message, "An Error Has Occured", MessageBoxButtons.OK, MessageBoxIcon.Error); 
                }
        }

        private void b_Results_Load_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdialog = new OpenFileDialog();
            ofdialog.Title = "Load Result";
            ofdialog.Filter = "Binary|*.bin|All files|*.*";
            ofdialog.Multiselect = false;
            if (ofdialog.ShowDialog(this) == DialogResult.OK)
            {
                try
                { mResultsCollection.Add(FileSerialization.DeSerializeObject<TestResult>(ofdialog.FileName)); }
                catch (Exception ex) {
                    MessageBox.Show(this, "An error occured during the load file operation.\r\n" + ex.Message, "An Error Has Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                SaveResultsTempFile();
            }
        }

        private void b_Results_Delete_Click(object sender, EventArgs e)
        {
            if (lb_ResultSets.SelectedIndex == -1)
                return;
            mResultsCollection.RemoveAt(lb_ResultSets.SelectedIndex);
            SaveResultsTempFile();
        }

        private void b_Results_ExportToFile_Click(object sender, EventArgs e)
        {
            if (lb_ResultSets.SelectedIndex == -1)
                return;
            SaveResults(mResultsCollection[lb_ResultSets.SelectedIndex], "FILE");
        }

        private void b_Results_ExportToDB_Click(object sender, EventArgs e)
        {
            if (lb_ResultSets.SelectedIndex == -1)
                return;
            SaveResults(mResultsCollection[lb_ResultSets.SelectedIndex], "DATABASE");
        }
        #endregion
        
        #region Tool / Menu bar
        private void tsb_New_Project_Click(object sender, EventArgs e)
        {
            if (!CheckSave())
                return;
            mTestDef = new TestDefinition();
            mFileInfo = null;
            mUnsavedChanges = false;
            RefreshTestDefView();
        }

        private void tsb_Open_Project_Click(object sender, EventArgs e)
        {
            if (mTestDef == null)
                return;
            if (!CheckSave())
                return;

            OpenFileDialog ofdialog = new OpenFileDialog();
            ofdialog.Title = "Open Project";
            ofdialog.Filter = "Scalability Project|*.spf|All files|*.*";
            ofdialog.Multiselect = false;
            if (ofdialog.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    mTestDef = FileSerialization.DeSerializeObject<TestDefinition>(ofdialog.FileName);
                    mFileInfo = new FileInfo(ofdialog.FileName);
                    mUnsavedChanges = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error Occured During Load Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                RefreshTestDefView();
            }
        }

        private void tsb_Save_Project_Click(object sender, EventArgs e)
        {
            SaveProject();
        }
        
        private void tsb_SaveAs_Click(object sender, EventArgs e)
        {
            SaveProject(true);
        }

        private void tsb_Run_Test_Click(object sender, EventArgs e)
        {
            RunTest();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        private void scenarioBuilderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ScenarioBuilder builder = new ScenarioBuilder();
            builder.ShowDialog(this);
        }        

        private void ApplicationForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!CheckSave())
                e.Cancel = true;
        }        

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutBox1().Show(this);
        }
        #endregion

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OptionsDialog options = new OptionsDialog();
            options.ShowDialog(this);
        }
    }
}
